/**
 * 
 */
package com.hawkfly.system.inputbox;

import java.util.HashMap;
import java.util.Map;

import com.wbcs.config.Config;
import com.wbcs.config.xml.XmlElementBean;
import com.wbcs.exception.WbcsConfigLoadingException;
import com.wbcs.system.ReportRequest;
import com.wbcs.system.component.application.report.abstractreport.AbsReportType;
import com.wbcs.system.inputbox.AbsInputBox;
import com.wbcs.system.inputbox.IInputBoxOwnerBean;
import com.wbcs.util.Consts_Private;
import com.wbcs.util.RegexTools;
import com.wbcs.util.Tools;

/**
 * UEdit富文本编辑器
 * @author hawkfly
 */
public class UEditRichTextBox extends AbsInputBox
{
    public UEditRichTextBox(String typename)
    {
        super(typename);
    }

    /* (non-Javadoc)
     * @see com.wbcs.system.inputbox.AbsInputBox#getIndependentDisplayString(com.wbcs.system.ReportRequest, java.lang.String, java.lang.String, java.lang.Object, boolean)
     */
    @Override
    public String getIndependentDisplayString(ReportRequest rrequest,String value,String dynstyleproperty,Object specificDataObj,boolean isReadonly)
    {
        
        return null;
    }

    /* (non-Javadoc)
     * @see com.wbcs.system.inputbox.AbsInputBox#doGetDisplayStringValue(com.wbcs.system.ReportRequest, java.lang.String, java.lang.String, boolean)
     */
    @Override
    protected String doGetDisplayStringValue(ReportRequest rrequest,String value,String style_property,boolean isReadonly)
    {
        StringBuffer resultBuf = new StringBuffer();
        resultBuf.append(this.getBeforedescription(rrequest));
        String inputboxid = getInputBoxId(rrequest);
        resultBuf.append("<textarea type='text/plain' typename='"+typename+"' name='"+inputboxid+"'  id='"+inputboxid+"' ");
        if(style_property!=null) resultBuf.append(" ").append(style_property);
        resultBuf.append(">").append(getInputBoxValue(rrequest,value)).append("</textarea>");
        resultBuf.append(this.getAfterdescription(rrequest));
        StringBuffer params = new StringBuffer();
        /*String configparams=Tools.replaceAll(this.inputboxparams,"#INPUTBOXID#",inputboxid);
        if(isReadonly)
        {
            configparams=Tools.replaceAll(configparams,"#READONLY#","true");
        }else
        {
            configparams=Tools.replaceAll(configparams,"#READONLY#","false");
        }*/
        //String configparams=Tools.replaceAll(this.inputboxparams,"#INPUTBOXID#",inputboxid);
        params.append("renderid:\"").append(inputboxid).append("\", configs:").append("{initialFrameHeight:100, initialFrameWidth: 300}");
        params.append(",onchange:");
        params.append("\"try{doAddDataForSaving('"
                +this.getOwner().getReportBean().getGuid()+"','true');}catch(e){logErrorsAsJsFileLoad(e);}\"");
        params.append(",options:{}");
        rrequest.getWResponse().addOnloadMethod("UE.init",params.toString(),true);
        return resultBuf.toString();
    }

    /* (non-Javadoc)
     * @see com.wbcs.system.inputbox.AbsInputBox#filledInContainer(java.lang.String)
     */
    @Override
    public String filledInContainer(String onblur)
    {
        // TODO Auto-generated method stub
        return "";
    }

    /* (non-Javadoc)
     * @see com.wbcs.system.inputbox.AbsInputBox#getDefaultStylePropertyForDisplayMode2()
     */
    @Override
    protected String getDefaultStylePropertyForDisplayMode2()
    {
        // TODO Auto-generated method stub
        return "";
    }

    /* (non-Javadoc)
     * @see com.wbcs.system.inputbox.AbsInputBox#getInputboxInnerType()
     */
    @Override
    public String getInputboxInnerType()
    {
        return "richtextbox";
    }

    @Override
	public String createGetValueByIdJs()
    {
       return "return UE.getEditor(id).getContent();";
    }
    
    @Override
	public String createGetValueByInputBoxObjJs()
    {
        StringBuffer resultBuf=new StringBuffer();
        resultBuf.append("if(fillmode==2){");
        resultBuf.append("  value=UE.getEditor('WX_RICHTEXT_BOX').getContent();label=value;");
        resultBuf.append("}else if(fillmode==1){");
        resultBuf.append("  value=UE.getEditor(boxObj.getAttribute('id')).getContent(); label=value;");
        resultBuf.append("}");
        return resultBuf.toString();
    }
    
    @Override
	public String createSetInputBoxValueByIdJs()
    {
       return "UE.getEditor(id).setContent(newvalue);";
    }
    
    @Override
	public void loadInputBoxConfig(IInputBoxOwnerBean ownerbean,XmlElementBean eleInputboxBean)
    {
        super.loadInputBoxConfig(ownerbean,eleInputboxBean);
        if(this.language!=null&&!this.language.trim().equals(""))
        {
            String dynparams=null;
            if(this.language.equals(Consts_Private.LANGUAGE_ZH))
            {
                dynparams="lang:'cn'";
            }else
            {
                dynparams="lang:'en'";
            }
            this.inputboxparams=Tools.mergeJsonValue(dynparams,this.inputboxparams);
        }
    }
    
    @Override
	public void doPostLoad(IInputBoxOwnerBean ownerbean)
    {
        super.doPostLoad(ownerbean);
        this.inputboxparams=Tools.mergeJsonValue("elements:'#INPUTBOXID#',readonly:#READONLY#,init_instance_callback:\"initTinymce\"",this.inputboxparams);
        String defaultparams=Config.getInstance().getResourceString(null,null,"${richtextbox.params.default}",false);
        if(defaultparams!=null&&!defaultparams.trim().equals(""))
        {
            defaultparams=Tools.formatStringBlank(defaultparams);
            this.inputboxparams=Tools.mergeJsonValue(defaultparams,this.inputboxparams);
        }
        this.inputboxparams=Tools.replaceAll(this.inputboxparams,"\"","'");//因为稍后要把它们显示在<span/>的一个属性中，因此出现了"号会有问题，对于json字符串，用"和用'意义一样，所以这里做替换
        this.inputboxparams="{"+this.inputboxparams+"}";
        String ueditorjs=Config.webroot;//Config.webroot+"/webresources/component/ueditor/";
        ownerbean.getReportBean().getPageBean().addMyJavascriptFile(ueditorjs+"webresources/jsplugins/ueditor/ueditor.config.js",0);
        ownerbean.getReportBean().getPageBean().addMyJavascriptFile(ueditorjs+"webresources/jsplugins/ueditor/ueditor.all.js",0);
        processRichTextBoxCssFiles(ownerbean);
    }
    
    private void processRichTextBoxCssFiles(IInputBoxOwnerBean ownerbean)
    {
        Map<String,String> mParams=new HashMap<String,String>();
        RegexTools.parseJsonValue(this.inputboxparams,mParams);
        if(mParams==null||mParams.size()==0) return;
        String themename=mParams.get("theme");
        themename=themename==null?"":themename.trim();
        if(themename.startsWith("'")&&themename.endsWith("'")) themename=themename.substring(1,themename.length()-1);
        if(themename.startsWith("\"")&&themename.endsWith("\"")) themename=themename.substring(1,themename.length()-1);
        String skinname=mParams.get("skin");
        skinname=skinname==null?"":skinname.trim();
        if(skinname.startsWith("'")&&skinname.endsWith("'")) skinname=skinname.substring(1,skinname.length()-1);
        if(skinname.startsWith("\"")&&skinname.endsWith("\"")) skinname=skinname.substring(1,skinname.length()-1);
        if(themename.equals("")||skinname.equals("")) return;
        String cssprex=Config.webroot;//Config.webroot+"/webresources/component/ueditor/themes/";
        //cssprex=Tools.replaceAll(cssprex,"//","/");
        ownerbean.getReportBean().getPageBean().addMyCss(cssprex+"webresources/jsplugins/ueditor/themes/iframe.css");
        ownerbean.getReportBean().getPageBean().addMyCss(cssprex+"webresources/jsplugins/ueditor/themes/default/dialogbase.css");
        ownerbean.getReportBean().getPageBean().addMyCss(cssprex+"webresources/jsplugins/ueditor/themes/default/css/ueditor.css");
    }
    
    @Override
	protected void addJsValidateOnBlurEvent(AbsReportType reportTypeObj,IInputBoxOwnerBean ownerbean)
    {
        Object reportid = reportTypeObj.getReportBean();
        if(this.fillmode==2) return;
        super.addJsValidateOnBlurEvent(reportTypeObj,ownerbean);
    }

    @Override
	protected void processStylePropertyForFillInContainer()
    {
        throw new WbcsConfigLoadingException("报表"+this.owner.getReportBean().getPath()+"对应的可编辑报表类型不支持富文本编辑器richtextbox");
    }

}

